package com.sxtyxt.online.file;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.sxtyxt.entity.City;
import com.sxtyxt.entity.ResultVo;
import com.sxtyxt.online.ActBase;
import com.sxtyxt.online.AppManager;
import com.sxtyxt.online.R;
import com.sxtyxt.online.SystemConst;
import com.sxtyxt.online.SystemEnv;
import com.sxtyxt.online.imagecrop.ActClipImage;
import com.sxtyxt.online.qrcode.MipcaActivityCapture;
import com.sxtyxt.util.FileUtil;
import com.sxtyxt.util.GsonUtil;
import com.sxtyxt.util.ImageLoaderUtil;
import com.sxtyxt.util.ImageUtil;
import com.sxtyxt.util.TextUtil;
import com.sxtyxt.volley.LoadingDialogResultListenerImpl;
import com.sxtyxt.volley.URL;
import com.sxtyxt.volley.VolleyUtils;
import com.sxtyxt.widget.ActionSheetDialog;
import com.sxtyxt.widget.ClearEditText;
import com.sxtyxt.widget.FloatingDialog;
import com.sxtyxt.widget.wheel.OnWheelChangedListener;
import com.sxtyxt.widget.wheel.OnWheelScrollListener;
import com.sxtyxt.widget.wheel.WheelView;
import com.sxtyxt.widget.wheel.adapter.MyCityAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/11.
 */

public class ActAddFileDetail extends ActBase implements View.OnClickListener, OnWheelChangedListener, OnWheelScrollListener {

    private LinearLayout layoutReceiveDistrict, layoutSenderDistrict;
    private ClearEditText etxtLogisticsId, etxtEndPersonName, etxtEndPersonTelephone, etxtEndPersonAddress;
    private ClearEditText etxtStartPersonName, etxtStartPersonTelephone, etxtStartPersonAddress;
    private TextView txtReceiveDistrict, txtSenderDistrict;
    private ClearEditText etxtGoods;
    private Button btnSave, btnGoodsPic, btnBoxPic, btnStartPersonIdCard;
    private ImageView ivGoodsPic, ivBoxPic, ivStartPersonIdCard;

    private String uploadBoxPicPath;
    private String uploadGoodsPicPath;
    private String uploadStartPersonIdCardPath;

    private String boxPicFilePath;
    private String goodsPicFilePath;
    private String startPersonIdCardFilePath;

    private ImageView imgScan;


    @Override
    protected void initUI() {
        super.initUI();

        etxtLogisticsId = (ClearEditText) findViewById(R.id.etxt_logisticsId);
        etxtEndPersonName = (ClearEditText) findViewById(R.id.etxt_endPerson_name);
        etxtEndPersonTelephone = (ClearEditText) findViewById(R.id.etxt_endPerson_telephone);
        etxtEndPersonAddress = (ClearEditText) findViewById(R.id.etxt_endPerson_address);
        etxtStartPersonName = (ClearEditText) findViewById(R.id.etxt_startPerson_name);
        etxtStartPersonTelephone = (ClearEditText) findViewById(R.id.etxt_startPerson_telephone);
        etxtStartPersonAddress = (ClearEditText) findViewById(R.id.etxt_startPerson_address);
        etxtGoods = (ClearEditText) findViewById(R.id.etxt_goods);

        btnSave = (Button) findViewById(R.id.btn_save);
        btnSave.setOnClickListener(this);
        btnBoxPic = (Button) findViewById(R.id.btn_box_pic);
        btnBoxPic.setOnClickListener(this);
        btnStartPersonIdCard = (Button) findViewById(R.id.btn_startPerson_idCard);
        btnStartPersonIdCard.setOnClickListener(this);
        btnGoodsPic = (Button) findViewById(R.id.btn_goods_pic);
        btnGoodsPic.setOnClickListener(this);

        ivGoodsPic = (ImageView) findViewById(R.id.iv_goods_pic);
        ivBoxPic = (ImageView) findViewById(R.id.iv_box_pic);
        ivStartPersonIdCard = (ImageView) findViewById(R.id.iv_startPerson_idCard);


        layoutReceiveDistrict = (LinearLayout) findViewById(R.id.layout_receive_district);
        layoutReceiveDistrict.setOnClickListener(this);
        layoutSenderDistrict = (LinearLayout) findViewById(R.id.layout_sender_district);
        layoutSenderDistrict.setOnClickListener(this);

        txtReceiveDistrict = (TextView) findViewById(R.id.txt_receive_district);
        txtSenderDistrict = (TextView) findViewById(R.id.txt_sender_district);

        if (SystemEnv.getAddress() != null && SystemEnv.getAddress().size() > 0) {
            provinces = SystemEnv.getAddress();
            initPickerView();
        } else {
            getCity();
        }

        imgScan = (ImageView) findViewById(R.id.img_scan);
        imgScan.setOnClickListener(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.file_details_add;
    }

    private int CLICK_IMAGE_ID;
    private int CLICK_DISTRICT_LAYOUT_ID;

    public static final int CLICK_BOX_PIC = 232;
    public static final int CLICK_GOODS_PIC = 233;
    public static final int CLICK_STARTPERSON_IDCARD = 234;

    public static final int CLICK_RECEIVE_DISTRICT_LAYOUT = 0;
    public static final int CLICK_SENDER_DISTRICT_LAYOUT = 1;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_box_pic:
                CLICK_IMAGE_ID = CLICK_BOX_PIC;
                selectBoxImg();
                break;
            case R.id.btn_goods_pic:
                CLICK_IMAGE_ID = CLICK_GOODS_PIC;
                selectBoxImg();
                break;
            case R.id.btn_startPerson_idCard:
                CLICK_IMAGE_ID = CLICK_STARTPERSON_IDCARD;
                selectBoxImg();
                break;
            case R.id.btn_save:
                saveFile();
                break;
            case R.id.layout_receive_district:
                CLICK_DISTRICT_LAYOUT_ID = CLICK_RECEIVE_DISTRICT_LAYOUT;
                if (cityDialog != null) {
                    cityDialog.show();
                }
                break;
            case R.id.layout_sender_district:
                CLICK_DISTRICT_LAYOUT_ID = CLICK_SENDER_DISTRICT_LAYOUT;
                if (cityDialog != null) {
                    cityDialog.show();
                }
                break;
            case R.id.img_scan:
                Intent intent = new Intent();
                intent.setClass(this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                break;

        }
    }

    private void selectBoxImg() {
        ActionSheetDialog photoDialog = new ActionSheetDialog(this);
        photoDialog.builder();
        photoDialog.setCancelable(true);
        photoDialog.setCanceledOnTouchOutside(true);
        photoDialog.addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                takeCapture();

            }

        });
        photoDialog.addSheetItem("从相册中选择", ActionSheetDialog.SheetItemColor.Black, new ActionSheetDialog.OnSheetItemClickListener() {

            @Override
            public void onClick(int which) {
                fromLocal();
            }

        });
        photoDialog.show();
    }

    private String filePath;


    /**
     * 拍照
     */
    private void takeCapture() {
        filePath = ImageUtil.getPicture(this);
    }


    /**
     * 本地选取
     */
    private void fromLocal() {
        ImageUtil.fromLocal(this);
    }

    private final static int SCANNIN_GREQUEST_CODE = 1;


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            switch (requestCode) {
                case ImageUtil.CAPTUR_FROM_LOCAL:
                    String uriOrPath = data.getDataString();
                    if (uriOrPath.contains("file://")) {
                        uriOrPath = uriOrPath.replace("file://", "");
                        filePath = uriOrPath;
                        transfer(ActClipImage.class, filePath, "PATH", CLICK_IMAGE_ID);
                        return;
                    }
                    Uri uri = data.getData();

                    if (uri != null) {

                        Log.i("uri", uri.toString());

                        ContentResolver cr = this.getContentResolver();

                        Cursor cursor = cr.query(uri, null, null, null, null);
                        if (cursor != null) {
                            if (cursor.moveToFirst()) {
                                int dataIndex = cursor.getColumnIndex("_data");
                                int mimeIndex = cursor.getColumnIndex("mime_type");
                                if (dataIndex >= 0)
                                    filePath = cursor.getString(dataIndex);
                                String mimeType = null;
                                if (mimeIndex >= 0) {
                                    mimeType = cursor.getString(mimeIndex);
                                }

                                cursor.close();
                                if (filePath != null) {
                                    transfer(ActClipImage.class, filePath, "PATH", CLICK_IMAGE_ID);
                                }

                            }

                        }
                    }

                    break;
                case ImageUtil.CAPTUR_FROM_CAMERA:
                    if (FileUtil.isExist(filePath)) {
                        ImageUtil.resetImageOrientation(filePath);
                        transfer(ActClipImage.class, filePath, "PATH", ActClipImage.CLIPIMAGE);

                    }
                    break;


                case CLICK_BOX_PIC:
                    // new path
                    String path = data.getStringExtra("bitmap");
                    System.out.println("path:" + path);
                    ImageLoader.getInstance().displayImage("file://" + path, ivBoxPic, ImageLoaderUtil.getOption(R.drawable.icon_box));
                    uploadBoxPicPath = path;
                    boxPicFilePath = filePath;
                    break;

                case CLICK_GOODS_PIC:
                    // new path
                    path = data.getStringExtra("bitmap");
                    System.out.println("path:" + path);
                    ImageLoader.getInstance().displayImage("file://" + path, ivGoodsPic, ImageLoaderUtil.getOption(R.drawable.icon_box));
                    uploadGoodsPicPath = path;
                    goodsPicFilePath = filePath;
                    break;
                case CLICK_STARTPERSON_IDCARD:
                    // new path
                    path = data.getStringExtra("bitmap");
                    System.out.println("path:" + path);
                    ImageLoader.getInstance().displayImage("file://" + path, ivStartPersonIdCard, ImageLoaderUtil.getOption(R.drawable.icon_box));
                    uploadStartPersonIdCardPath = path;
                    startPersonIdCardFilePath = filePath;
                    break;
                case SCANNIN_GREQUEST_CODE:
                    Bundle bundle = data.getExtras();
                    etxtLogisticsId.setText(bundle.getString("result"));
                    break;
                default:
                    break;

            }
    }


    private void saveFile() {


        if (TextUtils.isEmpty(getStringByUI(etxtLogisticsId))) {
            doToast("单号不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtEndPersonName))) {
            doToast("收件人姓名不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtEndPersonTelephone))) {
            doToast("收件人电话不能为空");
            return;
        }
        if (!TextUtil.isMobileNumber(getStringByUI(etxtEndPersonTelephone)) && !TextUtil.isTelephoneNumber(getStringByUI(etxtEndPersonTelephone))) {
            doToast("收件人电话格式不正确");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(txtReceiveDistrict))) {
            doToast("收件人所在地区不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtEndPersonAddress))) {
            doToast("收件详细地址不能为空");
            return;
        }

        if (TextUtils.isEmpty(getStringByUI(etxtStartPersonName))) {
            doToast("发件人姓名不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtStartPersonTelephone))) {
            doToast("发件人电话不能为空");
            return;
        }
        if (!TextUtil.isMobileNumber(getStringByUI(etxtStartPersonTelephone)) && !TextUtil.isTelephoneNumber(getStringByUI(etxtStartPersonTelephone))) {
            doToast("发件人电话格式不正确");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(txtSenderDistrict))) {
            doToast("发件人所在地区不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtStartPersonAddress))) {
            doToast("发件详细地址不能为空");
            return;
        }
        if (TextUtils.isEmpty(getStringByUI(etxtGoods))) {
            doToast("物品名称不能为空");
            return;
        }


        List<File> files = new ArrayList<File>();
        List<String> filePartNames = new ArrayList<String>();
        if (!TextUtils.isEmpty(uploadBoxPicPath)) {
            files.add(new File(boxPicFilePath));
            filePartNames.add("boxpic");
        }
        if (!TextUtils.isEmpty(uploadGoodsPicPath)) {
            files.add(new File(goodsPicFilePath));
            filePartNames.add("idpic");
        }

        if (!TextUtils.isEmpty(uploadStartPersonIdCardPath)) {
            files.add(new File(startPersonIdCardFilePath));
            filePartNames.add("idcard");
        }

        VolleyUtils.requestServiceWithFile(SystemConst.SAVE_FILE, URL.getSaveFileParams(getLoginUserId(), getStringByUI(etxtLogisticsId), getStringByUI(etxtEndPersonName),
                getStringByUI(etxtEndPersonTelephone), receiveProvinceId, receiveCityId, receiveAreaId, getStringByUI(etxtEndPersonAddress), getStringByUI(etxtStartPersonName), getStringByUI(etxtStartPersonTelephone),
                senderProvinceId, senderCityId, senderAreaId, getStringByUI(etxtStartPersonAddress), getStringByUI(etxtGoods)), filePartNames, files,

                new LoadingDialogResultListenerImpl(this, "正在提交数据") {
                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        ResultVo<?> vo = GsonUtil.deser(response, ResultVo.class);
                        if (vo == null) {
                            return;
                        }
                        if (vo.getResult() == 1) {
                            doToast("添加成功");
                            Intent intent = new Intent();
                            intent.putExtra("success", true);
                            setResult(RESULT_OK, intent);
                            AppManager.getAppManager().finishActivity(ActAddFileDetail.class);
                        } else {
                            doToast(vo.getMsg());
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                    }
                });
    }


    /*******
     * 第一步：选择城市代码开始
     ******/

    private WheelView provinceWheel;
    private List<City> provinces;
    private MyCityAdapter provinceAdapter = null;

    private WheelView cityWheel;
    private List<City> citys;
    private MyCityAdapter cityAdapter = null;

    private WheelView districtWheel;
    private List<City> districts;
    private MyCityAdapter districtAdapter = null;

    private int cityIndex = 0;
    private int provinceIndex = 0;
    private FloatingDialog cityDialog;

    private String receiveCityId, receiveAreaId, receiveProvinceId;
    private String senderCityId, senderAreaId, senderProvinceId;

    private void initPickerView() {
        if (cityDialog == null) {
            cityDialog = new FloatingDialog(this, R.style.dialogAnim_Wheel, Gravity.BOTTOM);
            cityDialog.setContentView(R.layout.comm_city_picker);
        }
        Button btnCancel = (Button) cityDialog.findViewById(R.id.btn_picker_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cityDialog.dismiss();
            }
        });
        Button btnOK = (Button) cityDialog.findViewById(R.id.btn_picker_ok);
        btnOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                cityDialog.dismiss();
                if (CLICK_DISTRICT_LAYOUT_ID == CLICK_RECEIVE_DISTRICT_LAYOUT) {
                    txtReceiveDistrict.setText(getWheelText(11) + "," + getWheelText(12) + "," + getWheelText(13));
                    receiveProvinceId = (String) provinceAdapter.getItemTag(provinceWheel.getCurrentItem());
                    receiveCityId = (String) cityAdapter.getItemTag(cityWheel.getCurrentItem());
                    receiveAreaId = (String) districtAdapter.getItemTag(districtWheel.getCurrentItem());
                } else {
                    txtSenderDistrict.setText(getWheelText(11) + "," + getWheelText(12) + "," + getWheelText(13));
                    senderProvinceId = (String) provinceAdapter.getItemTag(provinceWheel.getCurrentItem());
                    senderCityId = (String) cityAdapter.getItemTag(cityWheel.getCurrentItem());
                    senderAreaId = (String) districtAdapter.getItemTag(districtWheel.getCurrentItem());
                }
            }
        });
        provinceWheel = (WheelView) cityDialog.findViewById(R.id.picker_province);
        cityWheel = (WheelView) cityDialog.findViewById(R.id.picker_city);
        districtWheel = (WheelView) cityDialog.findViewById(R.id.picker_district);
        provinceWheel.addChangingListener(this);
        provinceWheel.addScrollingListener(this);
        cityWheel.addChangingListener(this);
        cityWheel.addScrollingListener(this);
        provinceAdapter = new MyCityAdapter(this, provinces);
        cityAdapter = new MyCityAdapter(this, citys);
        districtAdapter = new MyCityAdapter(this, districts);
        provinceWheel.setViewAdapter(provinceAdapter);
        cityWheel.setViewAdapter(cityAdapter);
        districtWheel.setViewAdapter(districtAdapter);


        updateCityPicker(cityWheel, 0);
        updateDistrictPicker(districtWheel, 0);


    }

    private void updateCityPicker(WheelView wheel, int index) {
        if (provinces != null && provinces.size() > 0) {
            citys = provinces.get(index).getChildern();
        } else {
            citys = new ArrayList<>();
        }

        cityAdapter = new MyCityAdapter(this, citys);
        cityWheel.setViewAdapter(cityAdapter);
        cityWheel.setCurrentItem(0);

        updateDistrictPicker(districtWheel, 0);

    }

    private void updateDistrictPicker(WheelView wheel, int index) {
        if (citys != null && citys.size() > 0) {
            districts = citys.get(index).getChildern();
        } else {
            districts = new ArrayList<>();
        }

        districtAdapter = new MyCityAdapter(this, districts);
        districtWheel.setViewAdapter(districtAdapter);
        districtWheel.setCurrentItem(0);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        switch (wheel.getId()) {
            case R.id.picker_city:
                cityIndex = newValue;
                break;
            case R.id.picker_province:
                provinceIndex = newValue;
                break;
            case R.id.picker_district:
                break;
            default:
                break;
        }
    }

    @Override
    public void onScrollingStarted(WheelView wheel) {

    }

    @Override
    public void onScrollingFinished(WheelView wheel) {
        switch (wheel.getId()) {
            case R.id.picker_province:
                updateCityPicker(cityWheel, provinceIndex);
                break;
            case R.id.picker_city:
                updateDistrictPicker(districtWheel, cityIndex);
                break;
            default:
                break;
        }
    }

    private String getWheelText(int type) {
        String text = "";
        switch (type) {
            case 11:// 省份
                text = provinceAdapter.getItemText(
                        provinceWheel.getCurrentItem()).toString();
                break;
            case 12:// 市
                text = cityAdapter.getItemText(cityWheel.getCurrentItem())
                        .toString();
                break;
            case 13:// 区、县
                text = districtAdapter.getItemText(
                        districtWheel.getCurrentItem()).toString();
                break;
            default:
                break;
        }

        return text;
    }

    private void getCity() {
        VolleyUtils.requestService(SystemConst.GET_CITY_URL, null, new LoadingDialogResultListenerImpl(this, "正在加载数据") {
            @Override
            public void onSuccess(String response) {
                super.onSuccess(response);
                CityVO vo = GsonUtil.deser(response, CityVO.class);
                if (vo == null) {
                    return;
                }
                if (vo.getResult() == 1) {
                    if (vo.getList() != null && vo.getList().size() > 0) {
                        provinces = vo.getList();
                        initPickerView();
                        SystemEnv.saveAddress(provinces);
                    }
                } else {
                    doToast(vo.getMsg());
                }
            }

            @Override
            public void onError() {
                super.onError();
            }
        });
    }

    class CityVO extends ResultVo<City> {

    }


}
